//
//  AppDelegate.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "AppDelegate.h"
#import"UMessage.h"
#import "MobClick.h"

#import "WXApi.h"
#import "WXApiObject.h"

#import "ZCMainVC.h"
#import "ZCSearchVC.h"
#import "ZCScanVC.h"
#import "ZCMeVC.h"
#import "ZCLoginVC.h"



@interface AppDelegate ()<UITabBarControllerDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.tabbarIndex = @"";
    [RegionManager initRegionManager];
    
    //友盟统计
    [self initMobClick];
    
    UITabBarController *tab_egt = [[UITabBarController alloc] init];
    self.tbc = tab_egt;
    tab_egt.tabBar.tintColor = [UIColor colorWithHexString:@"#03ab9e"];
    tab_egt.delegate = self;
    
    //主界面
    ZCMainVC *viewController_Nearby = [[ZCMainVC alloc] init];
    
    UINavigationController *nav_nearby = [[UINavigationController alloc] initWithRootViewController:viewController_Nearby];
    UITabBarItem *tabBar_Nearby = [[UITabBarItem alloc] initWithTitle:@"首页" image:[[UIImage imageNamed:@"tab_main_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:@"tab_main_p"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    nav_nearby.tabBarItem = tabBar_Nearby;
    
    //扫一扫
    ZCScanVC *MMM = [[ZCScanVC alloc] init];
    UINavigationController *nav_shareMMM = [[UINavigationController alloc] initWithRootViewController:MMM];
    UITabBarItem *tabBar_ShareMMM = [[UITabBarItem alloc] initWithTitle:@"扫一扫" image:[[UIImage imageNamed:@"tab_scan_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:@"tab_scan_p"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    nav_shareMMM.tabBarItem = tabBar_ShareMMM;
    
    //搜一搜
    ZCSearchVC *Msearch = [[ZCSearchVC alloc] init];
    UINavigationController *nav_searchMMM = [[UINavigationController alloc] initWithRootViewController:Msearch];
    UITabBarItem *tabBar_searchMMM = [[UITabBarItem alloc] initWithTitle:@"搜一搜" image:[[UIImage imageNamed:@"tab_search_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:@"tab_search_p"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    nav_searchMMM.tabBarItem = tabBar_searchMMM;
    
    //我
    ZCMeVC *viewController_Shake = [[ZCMeVC alloc] init];
    UINavigationController *nav_shake = [[UINavigationController alloc] initWithRootViewController:viewController_Shake];
    UITabBarItem *tabBar_Share = [[UITabBarItem alloc] initWithTitle:@"我" image:[[UIImage imageNamed:@"tab_me_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:@"tab_me_p"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    nav_shake.tabBarItem = tabBar_Share;
    
    //标签栏的合并4个内容
    NSMutableArray *muArr_tab = [[NSMutableArray alloc] initWithObjects:nav_nearby, nav_shareMMM,nav_searchMMM,nav_shake, nil];
    tab_egt.viewControllers = muArr_tab;
    
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigation_bg" ]forBarMetrics:UIBarMetricsDefault];
    
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    
    
    ZCMeVC *MEviewController = [[ZCMeVC alloc]init];

    _sideViewController=[[YRSideViewController alloc]initWithNibName:nil bundle:nil];
    _sideViewController.rootViewController=tab_egt;
    _sideViewController.rightViewController=MEviewController;
    
    
    _sideViewController.rightViewShowWidth=MeWeight;
    _sideViewController.needSwipeShowMenu=true;//默认开启的可滑动展示
    
    
    [_sideViewController setRootViewMoveBlock:^(UIView *rootView, CGRect orginFrame, CGFloat xoffset) {
        //使用简单的平移动画
        rootView.frame=CGRectMake(xoffset, orginFrame.origin.y, orginFrame.size.width, orginFrame.size.height);
    }];
    
    self.window.rootViewController=_sideViewController;
    self.window.backgroundColor = [UIColor whiteColor];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    
    [UMessage startWithAppkey:@"5617985fe0f55aef4500238c" launchOptions:launchOptions];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types (iOS 8.0以下)
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
#endif
    [UMessage setLogEnabled:YES];
    
    if ([WXApi registerApp:wxAppID]) {
        NSLog(@"微信支付注册成功！");
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)initMobClick{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick startWithAppkey:@"5617985fe0f55aef4500238c" reportPolicy:(ReportPolicy) REALTIME channelId:nil];
    [MobClick updateOnlineConfig];  //在线参数配置
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [UMessage registerDeviceToken:deviceToken];
    theAppdelegate.deviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                stringByReplacingOccurrencesOfString: @">" withString: @""]
                               stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"deviceToken = %@",theAppdelegate.deviceToken);
    
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //如果注册不成功，打印错误信息，可以在网上找到对应的解决方案
    //如果注册成功，可以删掉这个方法
    NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //关闭友盟自带的弹出框
    //    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if([sourceApplication isEqualToString:@"com.tencent.xin"])
    {
        return  [WXApi handleOpenURL:url delegate:WeichatManager];
    } else {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            //            NSLog(@"result = %@",resultDic);
//            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"AliPayResult" object:nil userInfo:resultDic];
//        }];
    }
    
    
    
    return YES;
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    int index = (int)tabBarController.selectedIndex;
    NSLog(@"asdfadf = %d",index);
    theAppdelegate.tabbarIndex = [NSString stringWithFormat:@"%d",index];
    if (index==3) {
        tabBarController.selectedIndex = 0;
        AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
        YRSideViewController *sideViewController=[delegate sideViewController];
        [sideViewController showRightViewController:YES];
    }
}

#pragma mark - wxpay

-(void) onResp:(BaseResp*)resp {
    if([resp isKindOfClass:[PayResp class]]) {
        resp = (PayResp *)resp;
        
        NSString *code = [NSString stringWithFormat:@"%d", resp.errCode];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPayResult" object:nil userInfo:@{@"payCode" : code}];
    }
}



@end
